<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="平台" prop="versionId">
        <el-select v-model="queryParams.platformType" placeholder="类型">
          <el-option
            v-for="platform in platformList"
            :key="platform.value"
            :label="platform.label"
            :value="platform.value"
          />
        </el-select>

      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="平台" align="center" prop="platformType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.autometion_config" :value="scope.row.platformType"/>
        </template>
      </el-table-column>
      <el-table-column label="版本号" align="center" prop="versionId"/>
      <el-table-column label="创建时间" align="center" prop="createTime"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 对话框 -->
    <el-dialog :title="title + '（拖动排序）'" :visible.sync="open" class="dialog" width="80%" append-to-body>
      <el-form label-width="80px" :model="ruleForm">
        <el-form-item label="平台">
          <el-select v-model="ruleForm.platformType" placeholder="请选择">
            <el-option
              v-for="dict in dict.type.autometion_config"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="版本号">
          <el-input style="width: 197px" v-model="ruleForm.versionId"></el-input>
        </el-form-item>
        <el-form-item label-width="0">
          <draggable
            v-model="ruleForm.details"
            transition-duration="200"
            :props="{ handle: '.drag-handle' }"
            @end="onDragEnd"
          >
            <el-form
              style="margin: 10px 0"
              :inline="true"
              v-for="(item, index) in ruleForm.details"
              :key="index"
            >
              <el-form-item label="按钮key" label-width="80px">
                <el-input class="key_inputA" v-model="item.buttonKey"></el-input>
              </el-form-item>
              <el-form-item label="按钮value">
                <el-input class="key_input" v-model="item.buttonValue"></el-input>
              </el-form-item>
              <el-form-item label="备注">
                <el-input class="key_inputA" v-model="item.notes"></el-input>
              </el-form-item>
              <el-form-item v-if="index + 1 == ruleForm.details.length">
                <el-button
                  class="addBtn"
                  size="mini"
                  type="primary"
                  @click="addDetail"
                >
                  +
                </el-button>
                <el-button
                  class="addBtn"
                  size="mini"
                  type="primary"
                  @click="removeDetail(index)"
                >
                  -
                </el-button>
              </el-form-item>
            </el-form>
          </draggable>

        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {list, get, deleted, add, update} from "@/api/system/autometion/index";
import draggable from 'vuedraggable'

export default {
  name: "Post",
  dicts: ['autometion_config'],
  components: {
    draggable,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 配置表格数据
      postList: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      dialogType: undefined,
      // 查询参数
      platformList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: 'createTime',
        isAsc: 'descending',
        platformType: "全部",
      },
      // 表单参数
      form: {},
      ruleForm: {
        id: undefined,
        versionId: "",
        platformType: "",
        details: [{buttonKey: "", buttonValue: "", notes: "", sortId: 0}],
      },
    };
  },
  created() {
    this.getList();
  },
  watch: {
    "dict.type.autometion_config"(newDict) {
      if (newDict && newDict.length > 0) {
        // 初始化 platformList 数组
        this.platformList = [];

        // 定义新的选项
        const newItem = {
          value: "-1",
          label: "全部"
        };

        // 将新选项添加到 platformList 的开头
        this.platformList.push(newItem);

        // 使用箭头函数遍历 newDict 并添加到 platformList
        newDict.forEach((item) => {
          this.platformList.push({
            value: item.value,
            label: item.label,
          });
        });

        // 设置默认值为新添加的选项的 value
        this.queryParams.platform = newItem.value;

        // 输出 platformList 以供调试
        console.log(this.platformList);
      }
    },},
    methods: {

      /** 查询平台配置列表 */
      getList() {
        this.loading = true;
        list(this.queryParams).then(response => {
          this.postList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
      },
      // 表单重置
      reset() {
        this.ruleForm = {
          id: undefined,
          versionId: "",
          platformType: "",
          details: [{buttonKey: "", buttonValue: "", notes: ""}],
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.postId)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        // this.reset();
        this.dialogType = 1
        this.open = true;
        this.title = "添加配置";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const postId = row.id;
        get(postId).then(response => {
          this.ruleForm = response;
          this.dialogType = 2
          this.open = true;
          this.title = "修改配置";
        });
      },
      /** 提交按钮 */
      submitForm: function () {
        if (this.dialogType == 2) {
          update(this.ruleForm).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
        } else {
          add(this.ruleForm).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const platformTypeLabel = this.selectDictLabel(this.dict.type.autometion_config, row.platformType);
        this.$modal.confirm('是否确认删除 [ ' + platformTypeLabel + " - " + row.versionId + ' ] 的数据项？').then(function () {
          return deleted(row.id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },

      /** 拖拽结束 */
      onDragEnd(event) {
        this.ruleForm.details.forEach((detail, index) => {
          detail.sortId = index + 1;
        });
      },
      /**新增条目 */
      addDetail() {
        this.ruleForm.details.push({
          buttonKey: '',
          buttonValue: '',
          notes: '',
          sortId: this.ruleForm.details.length + 1,
        })
      },
      /** 删除条目 */
      removeDetail(index) {
        if (this.ruleForm.details.length != 1) {
          this.ruleForm.details.splice(index, 1);
        }
      }
    }
  };
</script>
<style scope>
#sms {
  padding: 20px;

  .elPage_bar {
    margin-top: 20px;
  }
}

.el-tooltip__popper {
  max-width: 500px;
}

.demo-form-inline {
  display: flex;
  justify-content: space-between;
}

.Btn {
  width: 100px;
  height: 40px;
  font-size: 16px;
}

.key_inputA {
  width: 250px;
}

.key_input {
  width: 450px;
}
</style>
